/*
 * @Author: TLL
 * @Date: 2020-09-10 10:50:37
 * @version: v1.1
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-02-15 11:30:45
 * @Auditor: TLL
 */
import React, { useState, useEffect, useCallback, useImperativeHandle, forwardRef, useRef } from 'react';
import style from './search.module.scss';
import { Button } from 'antd';
import Input, { InputProps, SearchProps } from 'antd/lib/input';
import classnames from 'classnames';
import { Icon, history } from '@library';

const $t = window.$app.t;

interface AdvancedSearchProps {
  // 高级搜索方法
  advancedSearch?: () => void;
  advancedReset?: () => void;
  tableRef?: any;
}
export interface selectRefProps {
  resetKeyWords: () => void;
  resetScroll?: () => void;
  setValue?: any;
  setIsVisible?: any;
}

const Search = (props: InputProps & SearchProps & AdvancedSearchProps, ref: React.Ref<selectRefProps>) => {
  const { advancedReset: propAdvancedReset, advancedSearch: propAdvancedSearch, tableRef, ...searchProps } = props;
  const [isVisible, setIsVisible] = useState(false);
  const [value, setValue] = useState('');
  const [searchHeight, setSearchHeight] = useState("auto");

  const searchFormDiv = useRef<any>();

  useEffect(() => {
    if(props.suffix) {
      setTimeout(() => {  // 高级搜索条件数正好是3的倍数, 多添加一行
        const dom = searchFormDiv.current?.querySelector?.(".ant-form > .ant-row");
        if(dom?.childElementCount % 3 === 0) searchFormDiv.current.style.paddingBottom = '44px';
      }, 1000)
    }
  }, [props.suffix]);

  const stopPropagation = useCallback((e) => {
    e.nativeEvent.stopImmediatePropagation();
  }, []);

  const showSearchModal = useCallback((e) => {
    setIsVisible((bool) => {
      setTimeout(() => {
        const height = bool ? 0 : ((searchFormDiv.current?.getBoundingClientRect?.()?.height || 0) + 48);
        setSearchHeight(height)
        tableRef?.current?.resetScroll?.();
      }, 1)
      return !bool;
    })
    e.nativeEvent.stopImmediatePropagation();
  }, []);

  const advancedSearch = useCallback(() => {
    // setIsVisible(false);
    // setTimeout(() => { 
    //   setSearchHeight("auto");
    //   tableRef?.current?.resetScroll?.();
    // }, 1)
    propAdvancedSearch?.();
  }, [propAdvancedSearch]);

  const advancedReset = useCallback((e) => {
    // setIsVisible(false);
    // setTimeout(() => { 
    //   setSearchHeight("auto");
    //   tableRef?.current?.resetScroll?.();
    // }, 1)
    setValue('');
    e.nativeEvent.stopImmediatePropagation();
    propAdvancedReset?.();
  }, [propAdvancedReset]);

  const onKeyDown = useCallback(
    (e) => {
      if (e.keyCode === 13) props.onSearch?.(value?.trim());
    },
    [value, props.onSearch]
  );

  useImperativeHandle(ref, () => ({
    resetKeyWords: () => setValue(''),
    resetScroll: () => {
      setTimeout(() => {
        const height = (searchFormDiv.current?.getBoundingClientRect?.()?.height || 0) + 48;
        setSearchHeight(height)
        tableRef?.current?.resetScroll?.();
      }, 1)
    },
    setValue,
    setIsVisible: (visible: boolean) => {
      setIsVisible(visible);
      const height = (searchFormDiv.current?.getBoundingClientRect?.()?.height || 0) + 48;
      setSearchHeight(height)
      tableRef?.current?.resetScroll?.();
    }
  }));

  return (
    <div className={style.searchDiv} id={history.location.pathname}>
      <div className={`${style.searchComp} common-search`} style={{height: typeof searchHeight === "string" ? searchHeight : (searchHeight + "px")}}>
        <Input
          value={value}
          disabled={isVisible}
          placeholder={searchProps.placeholder}
          onChange={(e) => {
            setValue(e.target.value);
            props.onChange?.(e);
          }}
          onKeyDown={onKeyDown}
          allowClear
          suffix={<Icon style={{color: "#DEDEDF"}} icon="&#xe63b;" onClick={() => props.onSearch?.(value?.trim())} />}
          addonAfter={props.suffix ? <span className={style.cursorPointer} onClick={showSearchModal}>{$t('ADV')}</span> : null}
        />
        <div onClick={stopPropagation} ref={searchFormDiv} className={classnames(style.searchForm, { [style.showAdvanceModal]: isVisible })}>
          {
            props.suffix
              ? <>
                  {props.suffix}
                  <div className={style.searchBtnGroup}>
                    <Button type="primary" onClick={advancedSearch}>{$t('refer')}</Button>
                    <Button className={style.marginL8} onClick={advancedReset}>{$t('reset')}</Button>
                  </div>
                </>
              : null
          }
        </div>
      </div>
    </div>
  );
};

export default forwardRef(Search);
